<template>
  <div class="app">
    <el-header>
      <div style="display: flex; align-items: center;">
        <span style="margin-left: 10px;" @click="shouye()">
          <i class="el-icon-arrow-left"></i>服务门店
        </span>
      </div>
<!--      <div @click="aaaa()">-</div>-->
    </el-header>
    <div style="display: flex; align-items: center;">
      <div style="display: flex; align-items: center; margin-right: 20px;" class="container">
        <i class="el-icon-goods" style="margin-left: 20px;"></i> <span style="margin-left: 0;"> <span>{{ this.vehicles0.name }}</span></span>
      </div>
      <div style="display: flex; align-items: center;"  class="weizhi">
        <span style="margin-left: 140px;" @click="mendiandtxx()"><i class="el-icon-location"></i>{{this.city}}</span>
        <el-dropdown>
          <i class="el-icon-arrow-down el-dropdown-link"></i>
        </el-dropdown>
      </div>

    </div>
    <el-form :inline="true" :model="formm" class="sousuo" >
        <el-input v-model="formm.mdname" placeholder="🔍  请输入门店名称" clearable></el-input>
    </el-form>
    <div class="service-list">
      <van-tabs v-model="active1">
        <van-tab title="综合排序" >
          <div class="kuang1" >
          <van-cell-group v-for="item in vehicles1" >
            <van-card
                :tag="item.cishu==0?'':item.cishu==1?'去过':'常去'"
                :thumb="item.img"
                @click="details(item.mid)"
            > `
              <template #tags>
                <span class="x0">{{item.mdname}}</span><br><br>
                  <span class="x1">{{item.xingji }}</span>
                  <span class="x2">{{item.xingjishu }}.0&nbsp;&nbsp;&nbsp;</span>
                  <span class="x3">|&nbsp;&nbsp;&nbsp;{{item.danshu }}&nbsp;单</span><br><br><br>
                <span class="x4">{{item.pinlun}}</span>
                <span class="x5">
                  {{ (item.juli / 1000).toFixed(2) }} km</span>
              </template></van-card>
          </van-cell-group>
        </div>
        </van-tab>
        <van-tab title="距离排序">
          <div class="kuang1" >
          <van-cell-group v-for="item in vehicles2" :key="item.id">
            <van-card
                :tag="item.cishu==0?'':item.cishu==1?'去过':'常去'"
                :thumb="item.img"
                @click="details(item.mid)"
            >
              <template #tags>
                <span class="x0">{{item.mdname}}</span><br><br>
                <span class="x1">{{item.xingji }}</span>
                <span class="x2">{{item.xingjishu }}.0&nbsp;&nbsp;&nbsp;</span>
                <span class="x3">|&nbsp;&nbsp;&nbsp;{{item.danshu }}&nbsp;单</span><br><br><br>
                <span class="x4">{{item.pinlun}}</span>
                <span class="x5" >{{ (item.juli / 1000).toFixed(2) }} km</span>
              </template></van-card>
          </van-cell-group>
        </div></van-tab>
        <van-tab title="筛选"  >
          <van-dropdown-menu>
            <van-dropdown-item v-model="value2" @change="aaa" :options="option2" title="选择筛选内容"/>
          </van-dropdown-menu>
          <div class="kuang1">
            <van-cell-group v-for="item in vehicles">
              <van-card
                  :tag="item.cishu==0?'':item.cishu==1?'去过':'常去'"
                  :thumb="item.img"
                  @click="details(item.mid)"
              >
                <template #tags>
                  <span class="x0">{{ item.mdname }}</span><br><br>
                  <span class="x1">{{ item.xingji }}</span>
                  <span class="x2">{{ item.xingjishu }}.0&nbsp;&nbsp;&nbsp;</span>
                  <span class="x3">|&nbsp;&nbsp;&nbsp;{{ item.danshu }}&nbsp;单</span><br><br><br>
                  <span class="x4">{{ item.pinlun }}</span>
                  <span class="x5">{{ (item.juli / 1000).toFixed(2) }} km</span>
                </template>
              </van-card>
            </van-cell-group>
          </div>
        </van-tab>
      </van-tabs>
    </div>
    <van-tabbar v-model="active">
      <van-tabbar-item icon="home-o" @click="shouye()">首页</van-tabbar-item>
      <van-tabbar-item icon="apps-o" @click="fenlei()">分类</van-tabbar-item>
      <van-tabbar-item icon="shop-o" @click="">门店</van-tabbar-item>
      <van-tabbar-item icon="contact-o" @click="wode()">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import MapLoader from "@/views/mendian/util";

export default {
  data() {
    return {
      active1: 0,
      vehicles0:[],
      active: 2,
      vehicles: [],
      vehicles1: [],
      vehicles111: [],
      vehicles222: [],
      vehicles333: [],
      vehicles2: [],
      formm:{
        mdname:'',
      },
      mudidi: '',
      ff: [],
      a: '',
      R:'',
      Q:'',
// 经纬度
      Ra: '',
      Qa: '',
      city: '定位中...',
      // geocodes:[],
      value2: 0,
      option2: [
        { text: '未去', value: 1},
        { text: '去过', value: 3 },
        { text: '常去', value: 2 },

      ],
    }
  },

  watch:{
    formm:{
      deep:true,
      handler(){
        this.findMendianAll();
        this.zonghe();
        this.juli();

      }
    }
  },
  methods: {
    aaa(val){
      this.value2 = val
      this.fetchBackendData()
    },
    fetchBackendData() {
      this.axios.post(`http://1.94.221.254:9999/api-qcfw-mendian/mendian/fetchBackendData?value2=${this.value2}`).then(res => {

        this.vehicles = res.data
        console.log(this.vehicles)
      })
    },
    findMendianAll(){
      this.axios.post(`http://1.94.221.254:9999/api-qcfw-mendian/mendian/findMendianAll`,this.formm).then(res => {
        this.vehicles333 = res.data
        this.findMendianAll1(this.vehicles333);
            // this.vehicles = res.data
      })
    },
    findMendianAll1(vehicles333) {
      this.vehicles=[]
      vehicles333.forEach(item => {
        let isDuplicate = false;
        for (let j = 0; j < this.vehicles.length; j++) {
          // 使用严格相等比较mdname属性来判断是否重复
          if (this.vehicles[j].mdname === item.mdname) {
            isDuplicate = true;
            break;
          }
        }
        if (!isDuplicate) {
          this.vehicles.push(item);
        }

      });

    },
    zonghe(){
      this.axios.post('http://1.94.221.254:9999/api-qcfw-mendian/mendian/zonghe',this.formm).then(res => {
        this.vehicles111 = res.data
        this.zonghe1(this.vehicles111);
      })
    },
    zonghe1(vehicles111) {
      this.vehicles1=[]
      vehicles111.forEach(item => {
        let isDuplicate = false;
        for (let j = 0; j < this.vehicles1.length; j++) {
          // 使用严格相等比较mdname属性来判断是否重复
          if (this.vehicles1[j].mdname === item.mdname) {
            isDuplicate = true;
            break;
          }
        }
        if (!isDuplicate) {
          this.vehicles1.push(item);
        }
      });
      // console.log(1111111111);
      // console.log(this.vehicles1);
    },
    juli(){
      this.axios.post('http://1.94.221.254:9999/api-qcfw-mendian/mendian/juli',this.formm).then(res => {
        this.vehicles222 = res.data
        this.juli1(this.vehicles222);
        // this.vehicles2 = res.data
      })
    },
    juli1(vehicles222) {
      this.vehicles2=[]
      vehicles222.forEach(item => {
        let isDuplicate = false;
        for (let j = 0; j < this.vehicles2.length; j++) {
          // 使用严格相等比较mdname属性来判断是否重复
          if (this.vehicles2[j].mdname === item.mdname) {
            isDuplicate = true;
            break;
          }
        }
        if (!isDuplicate) {
          this.vehicles2.push(item);
        }
      });
    },
    details(mid){
      this.$router.push({path: '/mendianxq', query: {mid: mid}})
    },

    findOne() {
      this.axios.get(`http://1.94.221.254:9999/api/qcfw-home/home/vehicles/findOne`).then(res => {
        this.vehicles0 = res.data.data
      })
    },
    mendiandtxx(){
      this.$router.push('/mendiandtxx')
    },
    shouye() {
      this.$router.push('/shouye')
    },
    fenlei() {
      this.$router.push('/fenlei')
    },
    wode() {
      this.$router.push('/wode')
    },
    mendianditu(){
      // location.href=`https://lbs.amap.com/demo/javascript-api-v2/example/location/browser-location`
      this.$router.push('/mendianditu')
    },
    // aaaa() {
    //   this.$router.push('/juli')
    // },
    //获取当前地理位置
    addresaaa() {
      this.axios.get(`https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${this.abcde}&key=497c66a7bfeda317880776a6d296ca5f&radius=1000&extensions=all `)
          .then(res => {
            if (res.data && res.data.regeocode && res.data.regeocode.addressComponent) {
              // 获取区级，将获取到的区名称赋值给this.city
              this.city = res.data.regeocode.addressComponent.district;
              console.log("当前地理位置（区）：" + this.city);
            } else {
              console.error("返回数据格式不符合预期，无法获取区信息");
            }
          })
          .catch(error => {
            console.error("获取地理位置信息出错：", error);
          });
    },

      async fetchGeocodeData(value) {
      try {
        const res = await this.axios.get(`https://restapi.amap.com/v3/geocode/geo?address=${value}&output=JSON&key=497c66a7bfeda317880776a6d296ca5f`);
        console.log('网络请求返回的数据：', res.data);
        this.ff = res.data;
        this.a = this.ff.geocodes[0].location;
        await this.fanhui();
      } catch (error) {
        console.error('请求出现错误：', error);
      }
    },
// 返回多少米
    async fanhui() {
      const res = await this.axios.get(`https://restapi.amap.com/v3/distance?origins=${this.abcde}&destination=${this.a}&output=JSON&key=497c66a7bfeda317880776a6d296ca5f`);
        this.a = res.data.results[0].distance;// 使用 optional chaining 防止空值错误
    },

// 测修车店的距离
    async getjuliyy() {
      setTimeout(async () => {
        // 遍历所有修车店并计算距离
        for (const item of this.vehicles1) {
          const mudidi = item.mdname;
          console.log(mudidi)
          await this.fetchGeocodeData (mudidi);  // 等待 fetchGeocodeData  完成

            item.juli = this.a;

        }
      }, 500);
    },
    // 测修车店的距离
    async getjuliyy2() {
      setTimeout(async () => {
        // 遍历所有修车店并计算距离
        for (const item of this.vehicles2) {
          const mudidi = item.mdname;
          await this.fetchGeocodeData (mudidi);  // 等待 fetchGeocodeData  完成
          item.juli = this.a;  // 将计算的距离赋给修车店
        }
        this.vehicles2.sort((a, b) => a.juli - b.juli);
      }, 600);
    },
    // 测修车店的距离
    async getjuliyy3() {
      setTimeout(async () => {
        // 遍历所有修车店并计算距离
        for (const item of this.vehicles) {
          const mudidi = item.mdname;
          await this.fetchGeocodeData (mudidi);  // 等待 fetchGeocodeData  完成
          item.juli = this.a;  // 将计算的距离赋给修车店
        }

      }, 900);
    },
  },
  created() {
    this.findOne();
    this.findMendianAll();
    this.zonghe();
    this.juli();
    MapLoader();

    // 延迟获取地理位置
    setTimeout(() => {
      const Ra = sessionStorage.getItem("R");
      const Qa = sessionStorage.getItem("Q");
      if (Ra && Qa) {
        this.Ra = Ra;
        this.Qa = Qa;
        console.log("执行已完成");
        console.log("经度=====" + this.Ra);
        console.log("纬度=====" + this.Qa);
        this.abcde = this.Ra + ',' + this.Qa;
        console.log("合起来：" + this.abcde);
        this.addresaaa();
      } else {
        console.error("从sessionStorage获取地理位置数据失败，数据可能不存在或格式不正确");
        // 尝试重新获取地理位置信息并存储到sessionStorage
        this.reGetLocation().then(() => {
          const newRa = sessionStorage.getItem("R");
          const newQa = sessionStorage.getItem("Q");
          if (newRa && newQa) {
            this.Ra = newRa;
            this.Qa = newQa;
            this.abcde = this.Ra + ',' + this.Qa;
            this.addresaaa();
          } else {
            console.error("重新获取地理位置信息后，仍无法从sessionStorage获取到正确数据");
            // 可以继续添加更复杂的兜底逻辑，比如提示用户手动输入等
          }
        }).catch(error => {
          console.error("重新获取地理位置信息出错：", error);
        });
      }
    }, 1);
    this.getjuliyy();
    this.getjuliyy2();
    this.getjuliyy3();
    var token = localStorage.getItem('token');
    if (token === null) {
      this.$router.push('/');
    }
  }
};
</script>

<style>
.x5 {
  padding-left: 65px;
  margin-top: 2px;
}

.x0 {
  font-size: 15px;
}
.x1{
  padding-top: 5px;
}
.x2{
  padding-top: 3px;
  margin-left: 10px;
  color: #FB4D03;
}
.x3{
  padding-top: 1.5px;
}
.weizhi{
  //border: 1px solid #ccc;
  padding-left: 25px;
}
.x4{

  //width: 100px;
}
.sousuo {
  margin-top: 10px;
}
.service-list {
  padding: 10px;
}
span {
  display: inline-block;
  float: left
}
li {}
img {
  width: 90px;
  height: 100px;
  margin-bottom: 30px;
  padding-left: 0;
}
.x1{
  font-size: 7px;


}

</style>
